require "common/Define"
require "framework/BaseController"
require "FairyGUI"
require "FGUI/MailItem"

ExtensionMain = BaseController:New({mControllerName = "ExtensionMain"});

function ExtensionMain:Main()
	-- body
	ExtensionMain:Awake();
end

function ExtensionMain:Awake()
	Application.targetFrameRate = 60;
	Stage.inst.onKeyDown:Add(self.OnKeyDown);

	--
	UIPackage.AddPackage("UI/Extension");
	--CS.FairyGUI.UIObjectFactory.SetPackageItemExtension("ui://Extension/mailItem", type(MailItem));
	fgui.register_extension("ui://Extension/mailItem", MailItem);

	-- load ui
	local prePackageName = "UI/";
	local packageName = "Extension";
	UIPackage.AddPackage(prePackageName..packageName);

	local componentName = "Main";
	self.mainComponent = UIPackage.CreateObject(packageName, componentName).asCom;
	GRoot.inst:AddChild( self.mainComponent );

	self:OnViewCreated(self.mainComponent);
end

function ExtensionMain:OnKeyDown(context)
 	-- body
 	if (context.inputEvent.keyCode == KeyCode.Escape) then
		print "Exit Game!"
		Application.Quit();
	end
end

function ExtensionMain:InitView()
	local _list = self.mainComponent:GetChild("mailList").asList;
	for i = 0, 9, 1 do
		local item = _list:AddItemFromPool();
		print("item", item);
		item:setFetched(i % 3 == 0);
		item:setRead(i % 2 == 0);
		item:setTime("5 Nov 2015 16:24:33");
		item.title = "Mail title here";
	end

	_list:EnsureBoundsCorrect();
	local delay = 0;
	for i=0, 9, 1 do
		local item = _list:GetChildAt(i);
		if (_list:IsChildInView(item)) then
			item:PlayEffect(delay);
			delay = delay + 0.2;
		else
			break;
		end
	end
end